﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace Clandestine.Battle.Effects
{
    public class LightOrbs : BattleEffect
    {
        public override void Action(Combatant source, Combatant[] targets)
        {
            int noMain = 3;
            int mainSize = 200;
            int noSmall = 5;
            int smallSize = 30;
            int smallIncrement = 5;
            Random r = new Random((int)DateTime.Now.Ticks);

            // Setup main orbs
            ParticleThing[] main = new ParticleThing[noMain];
            for (int i = 0; i < noMain; i++)
            {
                main[i] = new ParticleThing(10);
                main[i].SetPosition(new Point(r.Next(0, Graphics.ScreenWidth), r.Next(Graphics.ScreenHeight)));
                main[i].GrowTo(mainSize, 1000);
            }
            Ticker.AddTimer(null, 10000, true);

            // Setup the small orbs
            List<ParticleThing> small = new List<ParticleThing>();
            for (int i = 0; i < noSmall; i++)
            {
                ParticleThing p = new ParticleThing(10);
                p.SetPosition(new Point(r.Next(0, Graphics.ScreenWidth), r.Next(Graphics.ScreenHeight)));
                p.GrowTo(smallSize, 150);
                small.Add(p);
            }
            Ticker.AddTimer(null, 150, true);

            // Destinations!
            float speed = 50f; // per second
            ParticleThing[] destinations = new ParticleThing[noSmall];
            for (int i = 0; i < noSmall; i++)
            {
                // Go through all the main ones and score how close it is
                int dest = -1; int minDist = int.MaxValue;
                for (int j = 0; j < noMain; j++)
                {
                    int distX = small[i].X - main[j].X;
                    int distY = small[i].Y - main[j].Y;
                    int dist = (int)Math.Sqrt((distX * distX) + (distY * distY));
                    if (dist < minDist)
                        dest = j;
                }

                small[i].MoveTo(new Point(main[dest].X, main[dest].Y), (int)((minDist / speed) * 1000));
                destinations[i] = main[dest];
            }

            // Setup a delegate for small orbs meeting their destination
            ReachedDestinationDelegate del = new ReachedDestinationDelegate(delegate(ParticleThing p)
                {
                    int i = small.IndexOf(p);
                    destinations[i].GrowBy(smallIncrement, 300);
                    small.Remove(p);
                    p.Dispose();
                });
            foreach (ParticleThing p in small)
                p.OnReachedDestination += del;

            // ..
            while (small.Count > 0)
                System.Threading.Thread.Sleep(100);

        }
    }
}
